#include<iostream>
#include<unistd.h>
#include<cstring>
#include<string>
#include<cerrno>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include <cassert>
#include<sys/stat.h>
using namespace std;



#define PATHNAME "."
#define PROJID 0x6666


const int gsize=4096;

key_t getkey()
{
    key_t key=ftok(PATHNAME,PROJID);
    if(key==-1)
    {
        std::cerr << "error" << errno << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

static int createShmHelper(key_t key, int size, int flag)
{
    int shmid = shmget(key, gsize, flag);
    if (shmid == -1)
    {
        cerr << "error" << errno << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}
// server端创建IPC_CREAT|IPC_EXCL
int creatShm(key_t key, int size)
{
    umask(0);
    return createShmHelper(key, gsize, IPC_CREAT | IPC_EXCL | 0666);
}
// client端获取 IPC_CREAT
int getShm(key_t key, int size)
{
    // umask(0);
    return createShmHelper(key, gsize, IPC_CREAT);
}

void delShm(int shmid)
{
    int n=shmctl(shmid,IPC_RMID,nullptr);
    assert(n != -1);
    (void)n;

}

char* attchShm(int shmid)
{
    char* start;
    start=(char*)shmat(shmid,nullptr,0);
    return start;

}

void detachShm(char* shmstart)
{
    int n=shmdt(shmstart);
    assert(n != -1);
    (void)n;
}